package task

import (
	// "sync"
	"time"

	"gitee.com/kobeyyf/mkm/service/model"
	// "xorm.io/xorm"
)

// 任务,
// 用于维护任务的 执行设备, 执行商品, 执行情况
type Task struct {
	info *model.Task

	isDone    bool
	doneCount int
	products  []*model.LogProduct

	deviceMap map[uint32]*Device
}

func NewTask(info *model.Task, devices []*model.Device, products []*model.LogProduct) *Task {

	t := &Task{
		info:      info,
		deviceMap: make(map[uint32]*Device, len(devices)),
		products:  products,
	}

	t.info.StartTime = time.Now().Unix()

	t.info.ProductCount = len(products)
	t.info.DeviceCount = len(devices)

	for _, d := range devices {
		t.deviceMap[d.DeviceId] = NewDevice(info.Retry, d, products)
	}

	return t
}

func (t *Task) Next(deviceId uint32) *model.LogProduct {
	p, has := t.deviceMap[deviceId]
	if !has {
		return nil
	}
	tmp := p.Next()
	if tmp != nil {
		return tmp
	}

	t.doneCount++
	// 完成所有任务
	if t.doneCount == len(t.deviceMap) {
		t.info.DoneTime = time.Now().Unix()
		t.isDone = true
		t.info.Status = model.STATUS_DONE
	}

	return nil

}

func (t *Task) IsDone() bool {
	if t.isDone {
		return true
	}
	// 判断是否超时
	if t.info.StopTime < time.Now().Unix() {
		for _, d := range t.deviceMap {
			d.Stop()
		}
		t.info.Status = model.STATUS_TIMEOUT
		return true
	}
	return false

}

func (t *Task) StatusAll() (bool, []*model.LogProductDevice) {
	list := make([]*model.LogProductDevice, 0, len(t.deviceMap)*len(t.products))
	for _, d := range t.deviceMap {
		_, logs := d.Status()
		list = append(list, logs...)

	}
	return t.IsDone(), list
}

func (t *Task) Status(deviceId uint32) (bool, []*model.LogProductDevice) {
	p, has := t.deviceMap[deviceId]
	if !has {
		return false, nil
	}
	return p.Status()
}
func (t *Task) AddDoneProdeuct(deviceId uint32, productId uint64, img string) {
	p, has := t.deviceMap[deviceId]
	if !has {
		return
	}
	p.AddDoneProdeuct(productId, img)
	return
}
